package billing.session;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import billing.mem.MemRMI;

public class MemSessionManager implements HttpSessionManager{

	private ServletContext servletContext;

	public String sessionKey = "sid";
	private int sessionTimeout = 60 * 10;
	public String cookieDomain = "test.com";
	public String cookiePath = "/";

	@Override
	public MemHttpSession newSession(String sessionId) {
		MemHttpSession session = new MemHttpSession(sessionId);
		session.setServletContext(servletContext);
		return session;
	}

	public MemHttpSession getSession(String sessionId) {
		if (null == sessionId || "".equals(sessionId.trim())) {
			return null;
		}

		Object object = MemRMI.get(sessionId);
		if (object == null) {
			return null;
		}
		MemHttpSession session = newSession(sessionId);
		if (object instanceof Map<?, ?>) {
			@SuppressWarnings("unchecked")
			Map<String, Object> sessionMap = (Map<String, Object>) object;
			session.getValueMap().putAll(sessionMap);
		}
		return session;
	}

	@Override
	public boolean exists(String sessionId) {
		if (null == sessionId || "".equals(sessionId.trim())) {
			return false;
		}
		return MemRMI.get(sessionId) != null;
	}

	@Override
	public void updateSession(HttpSession session) {
		MemHttpSession s = (MemHttpSession) session;
		if (s.isUpdated() == false) {
			s.update();
		}
	}

//	@Override
//	public void setServletContext(ServletContext servletContext) {
//		this.servletContext = servletContext;
//	}

	@Override
	public String getSessionKey() {
		return sessionKey;
	}

	public void setSessionKey(String sessionKey) {
		this.sessionKey = sessionKey;
	}

	@Override
	public int getSessionTimeout() {
		return sessionTimeout;
	}

	public void setSessionTimeout(int sessionTimeout) {
		this.sessionTimeout = sessionTimeout;
	}

	@Override
	public String getCookieDomain() {
		return cookieDomain;
	}

	public void setCookieDomain(String cookieDomain) {
		this.cookieDomain = cookieDomain;
	}

	@Override
	public String getCookiePath() {
		return cookiePath;
	}

	public void setCookiePath(String cookiePath) {
		this.cookiePath = cookiePath;
	}
	
	static final HttpSessionManager sessionMng = new MemSessionManager();
	public static HttpSessionManager getSessionManager() {
		return sessionMng;
	}
}
